package com.restfinder.user.service;

import java.io.Serializable;
import java.util.Date;

import lombok.extern.slf4j.Slf4j;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.restfinder.user.component.PasswordUtils;
import com.restfinder.user.dao.RoleDAO;
import com.restfinder.user.dao.UserDAO;
import com.restfinder.user.model.Role;
import com.restfinder.user.model.User;

@Service
@Transactional(rollbackFor=Exception.class)
@Slf4j
public class UserService implements Serializable {

	private static final long serialVersionUID = 1L;

	@Autowired
	private UserDAO userDAO;
	@Autowired
	private RoleDAO roleDAO;
	
	public void register(User user) throws Exception {
		if(!userDAO.isUsernameUnique(user.getUsername())){
			throw new Exception("User with the same username has been already registered.");
		}
		user.setJoinDate(new Date());
		user.setLastLoginDate(user.getJoinDate());
		Role userRole = roleDAO.getByCode("ROLE_USER");
		user.add(userRole);
		user.setPassword(PasswordUtils.encodePassword(user.getPassword()));
		userDAO.save(user);
	}
	
	public User getLoggedUser() throws Exception {
        String username = AuthenticationService.getAuthenticatedUsername();
        return userDAO.getUserByUsername(username);
	}
	

}
